package com.yangff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yangff.entity.admin.entity.Admin;
import com.yangff.entity.dto.AccountDTO;
import com.yangff.entity.user.entity.User;
import com.yangff.entity.user.entity.dto.UserDTO;
import com.yangff.entity.vo.JwtVo;
import com.yangff.mapper.UserMapper;
import com.yangff.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangff.utils.JwtUtil;
import com.yangff.utils.MathUtil;
import com.yangff.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

/**
 * <p>
 * 存储用户基本信息 服务实现类
 * </p>
 *
 * @author yangff
 * @since 2025-01-14
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final RabbitTemplate rabbitTemplate;

    @Override
    public User updateUserByAccount(UserDTO user) {
        User use = getOne(new LambdaQueryWrapper<User>().eq(User::getAccount,user.getAccount()));
        if(user.getEmail() != null)use.setEmail(user.getEmail());
        if(user.getPhoneNumber() != null) use.setPhoneNumber(user.getPhoneNumber());
        if(user.getUsername() != null) use.setUsername(user.getUsername());
        if(user.getBankCard() != null) use.setBankCard(user.getBankCard());
        if(user.getTotalAssets() != null) use.setFluidMoney(user.getTotalAssets());

        return use;
    }

    @Override
    public JwtVo login(AccountDTO accountDTO) throws Exception {
        User one = getOne(new LambdaQueryWrapper<User>().eq(User::getAccount, accountDTO.getAccount()));


        JwtVo jwtVo = new JwtVo();
        try
        {
            if(MathUtil.checkSHA256(accountDTO.getPassword() , one.getPassword()) == true)
            {
                String token = JwtUtil.createJwtToken(accountDTO.getAccount(), "user", JwtUtil.DEFAULT_TIME);

                jwtVo.setAccount(accountDTO.getAccount());
                jwtVo.setToken(token);
                jwtVo.setType("user");
                rabbitTemplate.convertAndSend("fts.direct","save_usertoken",jwtVo);
            }
        }
        catch (Exception e)
        {
            //用户登录不成功
        }

        return jwtVo;
    }



}
